package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.admin.dto.LoginDto;
import com.heima.article.entity.ApAuthor;
import com.heima.article.feign.ArticleFeign;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.enums.UserEnum;
import com.heima.common.util.AppJwtUtil;
import com.heima.common.util.UserThreadLocalUtil;
import com.heima.media.entity.WmUser;
import com.heima.user.dto.FollowBehaviorDto;
import com.heima.user.dto.UserRelationDto;
import com.heima.user.entity.ApUser;
import com.heima.user.entity.ApUserFollow;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.IApUserFollowService;
import com.heima.user.service.IApUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-01-14
 */
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements IApUserService {

    @Autowired
    private ArticleFeign articleFeign;

    @Autowired
    private IApUserFollowService userFollowService;


    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;


    /**
     * 用户关注行为话题
     */
    @Value("${topic.followBehaviorTopic}")
    private String followBehaviorTopic;


    /**
     * APP端登录功能 考虑情况：1手机号密码登录   2手机设备ID进行登录
     *
     * @param dto 入参信息 手机号，密码，手机设备
     * @return {"user":{},"token":""}
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        //1.判断登录参数是否合法
        if (dto == null || (StringUtils.isBlank(dto.getPhone()) && StringUtils.isBlank(dto.getPassword()) && StringUtils.isBlank(dto.getEquipmentId()))) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2.手机号密码登录：根据APP人员账户查询自媒体人员信息
        if (StringUtils.isNotBlank(dto.getPhone()) && StringUtils.isNotBlank(dto.getPassword())) {
            LambdaQueryWrapper<ApUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ApUser::getPhone, dto.getPhone());
            ApUser one = this.getOne(queryWrapper);
            if (one == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //3.判断用户填写密码是否跟真实一致
            String pwdStr = dto.getPassword() + one.getSalt();
            String userEnterPwdEncodedStr = DigestUtils.md5DigestAsHex(pwdStr.getBytes());
            if (!one.getPassword().equals(userEnterPwdEncodedStr)) {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //4.认证通过后，基于JWT工具类生成用户jwt令牌 载荷中包含：userId userName 属性
            HashMap<String, Object> claimMaps = new HashMap<>();
            //TODO 返回令牌中载荷信息 userId 值为：APP用户ID
            claimMaps.put("userId", one.getId());
            claimMaps.put("userName", one.getName());
            String token = AppJwtUtil.getToken(claimMaps);

            //5.封装响应数据（对象中包含两个属性：user token）
            //5.1 封装响应结果中用户信息（一定要记得对敏感隐私数据做脱敏处理）
            one.setSalt(null);
            one.setPassword(null);
            one.setPhone(null);
            //5.2 封装响应结果中令牌信息

            //5.3 封装响应结果对象
            HashMap<String, Object> mapResult = new HashMap<>();
            mapResult.put("user", one);
            mapResult.put("token", token);
            return ResponseResult.okResult(mapResult);
        }
        //3.手机设备登录：点击“先看看”  jwt令牌中用户ID设置为“0”
        if (StringUtils.isNotBlank(dto.getEquipmentId())) {
            HashMap<String, Object> claimMaps = new HashMap<>();
            claimMaps.put("userId", 0);
            String token = AppJwtUtil.getToken(claimMaps);
            HashMap<String, Object> mapResult = new HashMap<>();
            mapResult.put("token", token);
            return ResponseResult.okResult(mapResult);
        }

        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
    }


    /**
     * 登录用户关注/取消关注 某个作者
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult follow(UserRelationDto dto) {
        //1.获取登录APP用户
        User user = UserThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //2.构建用户关注实体类
        ApUserFollow apUserFollow = new ApUserFollow();
        //2.1 设置当前登录用户信息
        apUserFollow.setUserId(user.getUserId());
        apUserFollow.setUserName(user.getUserName());

        //2.2 设置关注目标作者信息
        //2.2.1 远程调用文章微服务得到作者信息
        ResponseResult<ApAuthor> responseResult = articleFeign.getAuthorById(dto.getAuthorId());
        if (responseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            ApAuthor apAuthor = responseResult.getData();
            apUserFollow.setFollowId(apAuthor.getUserId());
            apUserFollow.setFollowName(apAuthor.getName());

            apUserFollow.setLevel(UserEnum.USER_FOLLOW_LEVEL_ONCE.getVal());

            //3.根据用户操作类型：新增关注记录或者关注记录
            LambdaQueryWrapper<ApUserFollow> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ApUserFollow::getUserId, user.getUserId());
            queryWrapper.eq(ApUserFollow::getFollowId, apAuthor.getUserId());
            //3.1 判断用户操作动作：关注 取消关注
            if (dto.getOperation().equals(UserEnum.USER_FOLLOW_OPRATION.getVal())) {
                //3.1.1 关注
                ApUserFollow one = userFollowService.getOne(queryWrapper);
                if (one == null) {
                    //第一次关注 保存
                    userFollowService.save(apUserFollow);
                }
            } else {
                //3.1.2 取消关注
                userFollowService.remove(queryWrapper);
            }

            //4.发送关注行为消息到kafka，将来行为微服务中监听消息 保存用户关注行为
            FollowBehaviorDto followBehaviorDto = new FollowBehaviorDto();
            followBehaviorDto.setUserId(user.getUserId());
            followBehaviorDto.setFollowId(apAuthor.getUserId());
            followBehaviorDto.setEquipmentId(dto.getEquipmentId());
            followBehaviorDto.setOperation(dto.getOperation());
            kafkaTemplate.send(followBehaviorTopic, JSON.toJSONString(followBehaviorDto));
        }
        return ResponseResult.okResult();
    }
}
